#include <math.h>
#include <iostream>

#include "draw_scenario.hpp"
#include "hex_geometry.hpp"
#include "raster.hpp"
#include "scenario.hpp"

namespace game {

namespace {
int scrollx, scrolly;
int cycle;
int scrollx_target = -1, scrolly_target = -1;
}

int scroll_x() { return scrollx; }
int scroll_y() { return scrolly; }
void scroll_to(int x, int y) { scrollx = x; scrolly = y; }
void set_scroll_target(int x, int y)
{
	scrollx_target = x;
	scrolly_target = y;
}

void set_scroll_target(const hex::location& loc)
{
	const int center_x = tile_pixel_x(loc) + HexWidth/2;
	const int center_y = tile_pixel_y(loc) + HexHeight/2;
	set_scroll_target(center_x - graphics::screen_width()/2,
	                  center_y - graphics::screen_height()/2);
}

bool is_scrolling_to_target()
{
	return scrollx_target != -1;
}

int draw_cycle() { return cycle; }
void next_draw_cycle() {
	++cycle;

	if(scrollx_target != -1 && scrolly_target != -1) {
		const int diff_x = scrollx_target - scrollx;
		const int diff_y = scrolly_target - scrolly;
		
		if(abs(diff_x) < 3 && abs(diff_y) < 3) {
			scrollx = scrollx_target;
			scrolly = scrolly_target;

			scrollx_target = -1;
			scrolly_target = -1;
		} else {
			scrollx += diff_x/10;
			scrolly += diff_y/10;

			if(diff_x != 0 && abs(diff_x) < 30) {
				scrollx += 3 * (diff_x > 0 ? 1 : -1);
			}

			if(diff_y != 0 && abs(diff_y) < 30) {
				scrolly += 3 * (diff_y > 0 ? 1 : -1);
			}
		}
	}
}

}
